package com.daocao.ds.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.daocao.ds.MainActivity;
import com.daocao.ds.R;
import com.daocao.ds.activity.SnatchingModeSettingActivity;
import com.daocao.ds.adapter.TabTopAdapter;
import com.daocao.ds.api.Api;
import com.daocao.ds.api.bean.RuleSwitchBean;
import com.daocao.ds.constant.UserInfoGlobal;
import com.daocao.ds.event.UserEvent;
import com.daocao.ds.util.Dialog;
import com.daocao.ds.util.Network;
import com.daocao.ds.util.RxLifeUtil;
import com.daocao.ds.util.ToastUtil;
import com.daocao.ds.util.UI;
import com.daocao.ds.util.Util;
import com.daocao.ds.view.HomeViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 18-11-16.
 */

public class HomeFragment extends BaseFragment {
    @BindView(R.id.btn_left)
    TextView btnLeft;
    @BindView(R.id.btn_right)
    TextView btnRight;
    @BindView(R.id.tablayout)
    RecyclerView tablayout;
    @BindView(R.id.pager)
    HomeViewPager pager;
    Unbinder unbinder;
    @BindView(R.id.txt_qua)
    SuperButton txtQua;
    private TabTopAdapter TabAdapter;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        TabAdapter = new TabTopAdapter(getContext());
        TabAdapter.setOnChooseListener(new TabTopAdapter.OnChooseListener() {
            @Override
            public void onClick(int poi) {
                pager.setCurrentItem(poi);
            }
        });
        tablayout.setLayoutManager(new GridLayoutManager(getContext(), 3));
        tablayout.setAdapter(TabAdapter);
        List<String> tab_titles = new ArrayList<>();
        tab_titles.add("可抢单");
        tab_titles.add("全部");
        tab_titles.add("已被抢单");
        TabAdapter.update(tab_titles);


        Fragment[] fragments = new Fragment[3];
        for (int i = 0; i < 3; i++) {
            HomeOrderFragment fragment = new HomeOrderFragment();
            Bundle bundle = new Bundle();
            // 状态： 0-全部，1-可抢、2 - 锁定，不可抢，3-已抢
            if (i == 0) {
                bundle.putInt("id", 1);
            } else if (i == 1) {
                bundle.putInt("id", 0);
            } else if (i == 2) {
                bundle.putInt("id", 3);
            }

            fragment.setArguments(bundle);
            fragments[i] = fragment;
        }

        pager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {

            @Override
            public Fragment getItem(int position) {
                return fragments[position];
            }

            @Override
            public int getCount() {
                return fragments.length;
            }
        });
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(UserEvent event) {
        if (event.item.loaner.auto_loan_rule.equals("ON")) {
            btnRight.setText("关闭自动抢单模式");
            txtQua.setVisibility(View.VISIBLE);
            txtQua.setText(Util.getNumber(event.item.loaner.balances) + "\n上限额度剩余");
        } else {
            btnRight.setText("开启自动抢单模式");
            txtQua.setVisibility(View.GONE);
        }
    }

    public void getRuleSwitch(boolean oepn) {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.makeText(getContext(), "网络连接失败").show();
            return;
        }
        ((MainActivity) getActivity()).loadingDialog.show();
        RuleSwitchBean bean = new RuleSwitchBean();
        if (oepn) {
            bean.open = "ON";
        } else {
            bean.open = "OFF";
        }
        Api.api_service.getRuleSwitch(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        ((MainActivity) getActivity()).loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (oepn) {
                        btnRight.setText("关闭自动抢单模式");
                        ToastUtil.makeText(getContext(), "开启成功");
                    } else {
                        btnRight.setText("开启自动抢单模式");
                        ToastUtil.makeText(getContext(), "关闭成功");
                    }
                    UserInfoGlobal.saveAutoRule(bean.open);
                });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @OnClick(R.id.btn_right)
    public void onViewClicked() {
        if (UI.toString(btnRight).equals("关闭自动抢单模式")) {
            Dialog.showDefaultDialog(getContext(), "", "关闭自动抢单模式后，不能及时抢单喔，您确定要关闭吗？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    getRuleSwitch(false);
                }

                @Override
                public void cancel() {

                }
            });
        } else {
            Util.startActivity(getContext(), SnatchingModeSettingActivity.class);
        }
    }
}
